package com.shenzhen.horselive.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.AuctionDetailsAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AuctionDetailsRecordList;
import com.shenzhen.horselive.beans.ExptimeBean;
import com.shenzhen.horselive.beans.MyCityBean;
import com.shenzhen.horselive.beans.MyCityDetailsBean;
import com.shenzhen.horselive.databinding.ActivityMyCityDetailsBinding;
import com.shenzhen.horselive.databinding.HeadAuctionDetailsBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.utils.TimeUtils;

import java.sql.Time;

import io.reactivex.internal.observers.LambdaObserver;

/**
 * 我的主城详情
 */
public class MyCityDetailsActivity extends AppBarActivity {

    ActivityMyCityDetailsBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding =ActivityMyCityDetailsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleRed();
        setTitle("我的主城");
        initViews();
//        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        String  id = getIntent().getStringExtra("id");
        if (id==null)
            return;
        ApiFactory.getApiService().myCityDetails(User.get().getMyInfo().getToken(),
                id).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<MyCityDetailsBean>(this) {
                    @Override
                    protected void onNextInActive(MyCityDetailsBean myCityDetailsBean) {
                        if (myCityDetailsBean.isSuccess())
                        {
                            //填充数据城市的状态 1盈利中 2拍卖中 3已售出 4已回收
                            int  staues = myCityDetailsBean.getData().getStatus();
                            if (headbinding!=null)
                            {
                                headbinding.tvAddr.setText(myCityDetailsBean.getData().getAreaName());
                            }
                            binding.btGo.setEnabled(true);
                            switch (staues)
                            {
                                case 1:
                                    //倒计时控件
                                    headbinding.containerTime.setVisibility(View.VISIBLE);
                                    //计算间隔时间开始倒计时
                                    countDowm(myCityDetailsBean.getData().getExpireTime());
                                    //盈利中
                                    headbinding.imgState.setImageResource(R.mipmap.ico_mycity_yinglizhi);
                                    //文字
                                    headbinding.tvTextText.setText("竞拍价格：");
                                    headbinding.tvTextText1.setText("竞拍时间：");
                                    headbinding.tvTextText2.setText("解锁时间：");
                                    headbinding.tvTextText3.setText("当前总收益：");
                                    headbinding.tvTextText3.setVisibility(View.VISIBLE);
                                    //数字
                                    headbinding.tvValue.setText(myCityDetailsBean.getData().getPrice()+"(蜂值)");
                                    headbinding.tvValue1.setText(myCityDetailsBean.getData().getAuctionTime());
                                    //过期时间
                                    headbinding.tvValue2.setText(myCityDetailsBean.getData().getExpireTime());
                                    headbinding.tvValue3.setVisibility(View.VISIBLE);
                                    headbinding.tvValue3.setText(myCityDetailsBean.getData().getProfit()+"(蜂值)");

                                    headbinding.tvText1.setVisibility(View.GONE);
                                    //按钮上方的文字的处理
                                    binding.tvNotice.setVisibility(View.VISIBLE);
                                     getNotices(id);
                                     //按钮的处理
                                    binding.btGo.setText("到期继续锁城");

                                    if ("1".equals(myCityDetailsBean.getData().getCanLock())
                                            ||"true".equals(myCityDetailsBean.getData().getCanLock()))
                                {
                                    binding.btGo.setEnabled(true);
                                }
                                    else
                                    {
                                        binding.btGo.setEnabled(false);
                                    }

                                    //继续锁车
                                    binding.btGo.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                          if ("1".equals(myCityDetailsBean.getData().getCanLock())
                                          ||"true".equals(myCityDetailsBean.getData().getCanLock())
                                          )
                                          {
                                              //可以继续锁城市
                                              ContinueLockCityActivity.start(getContext(),myCityDetailsBean.getData().getCityMasterId()+"");
                                          }
                                          else
                                          {
                                              //暂时不可以锁城市
                                              binding.btGo.setEnabled(false);
                                          }
                                        }
                                    });

                                    break;
                                case 2:
                                    //拍卖中
                                    headbinding.imgState.setImageResource(R.mipmap.ico_paimaizhong);

                                    //文字
                                    headbinding.tvTextText.setText("城市总收益：");
                                    headbinding.tvTextText1.setText("起拍价：");
                                    headbinding.tvTextText2.setText("剩余竞拍时间：");
                                    //数字
                                    headbinding.tvValue.setText(myCityDetailsBean.getData().getLastProfit()+"蜂值");
                                    headbinding.tvValue1.setText(myCityDetailsBean.getData().getStartPrice()+"蜂值");
                                    headbinding.tvValue2.setText(myCityDetailsBean.getData().getResidueAuctionTime());

                                    //获取竞拍的记录列表
                                    getRecordList(myCityDetailsBean.getData().getAuctionSerialNum());

                                    binding.btGo.setText("参与城市竞拍");
                                    binding.btGo.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            PayAuctionCityActivity.start(getContext(),id);
                                        }
                                    });
                                    break;
                                case 3:
                                    //已经售出
                                    headbinding.imgState.setImageResource(R.mipmap.ico_yishouchu);
                                    //文字
                                    headbinding.tvTextText.setText("现任城主：");
                                    headbinding.tvTextText1.setText("成交价：");
                                    headbinding.tvTextText2.setVisibility(View.GONE);
//                                    headbinding.tvTextText2.setTextColor(getResources().getColor(R.color.red_common));

                                    //数字
                                    headbinding.tvValue.setText(myCityDetailsBean.getData().getUserName());
                                    headbinding.tvValue1.setText(myCityDetailsBean.getData().getPrice()+"蜂值");
                                    headbinding.tvValue2.setVisibility(View.GONE);
//                                    headbinding.tvValue2.setTextColor(getResources().getColor(R.color.red_common));

                                    //隐藏按钮
                                    binding.btGo.setVisibility(View.GONE);
                                    getRecordList(myCityDetailsBean.getData().getAuctionSerialNum());
                                    break;
                                case 4:
                                    //已回收
                                    headbinding.imgState.setImageResource(R.mipmap.ico_yihuishou);
                                    headbinding.tvTextText.setText("城市总收益：");
                                    headbinding.tvTextText1.setText("起拍价：");
                                    headbinding.tvTextText2.setText("当前下跌：");
                                    headbinding.tvTextText3.setText("剩余价值：");
                                    headbinding.tvTextText3.setVisibility(View.VISIBLE);
                                    headbinding.tvValue.setText(myCityDetailsBean.getData().getLastProfit()+"蜂值");
                                    headbinding.tvValue1.setText(myCityDetailsBean.getData().getStartPrice()+"蜂值");
                                    headbinding.tvValue2.setText(myCityDetailsBean.getData().getCurrentDown()+"蜂值");
                                    headbinding.tvValue2.setTextColor(getResources().getColor(R.color.red_common));
                                    headbinding.tvValue3.setText(myCityDetailsBean.getData().getResiduePrice()+"蜂值");
                                    headbinding.tvValue3.setVisibility(View.VISIBLE);
                                    headbinding.tvValue3.setTextColor(getResources().getColor(R.color.red_common));
                                    binding.btGo.setVisibility(View.GONE);
                                    break;
                            }

                        }else
                        {
                            showToast(myCityDetailsBean.getErrMessage());
                        }
                    }
                });
    }

    private CountDownTimer  countDownTimer;
    //倒计时控件
    private void countDowm(String endDate) {
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer=null;
        }

        if (countDownTimer==null)
        {
            countDownTimer= new CountDownTimer(TimeUtils.betweenNowDate(endDate),1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    //显示数字
                    if (headbinding!=null)
                    {
                        headbinding.tvDay.setText(TimeUtils.getDay(millisUntilFinished)+"");
                        headbinding.tvHour.setText(((int) TimeUtils.getHH(millisUntilFinished)/10)+"");
                        headbinding.tvHour1.setText((TimeUtils.getHH(millisUntilFinished)%10)+"");
                        //分钟
                        headbinding.tvMm.setText(((int) TimeUtils.getmm(millisUntilFinished)/10)+"");
                        headbinding.tvMm1.setText((TimeUtils.getmm(millisUntilFinished)%10)+"");
                        //秒
                        headbinding.tvSs.setText(((int) TimeUtils.getss(millisUntilFinished)/10)+"");
                        headbinding.tvSs1.setText((TimeUtils.getss(millisUntilFinished)%10)+"");

                    }
                }
                @Override
                public void onFinish() {
                  //刷新数据
                    initData();
                }
            };
            countDownTimer.start();
        }



    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer=null;
        }
    }

    private void getRecordList(String id) {
        ApiFactory.getApiService().auctionDetailsRecordList(User.get().getMyInfo().getToken()
                ,id).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AuctionDetailsRecordList>(this) {
                    @Override
                    protected void onNextInActive(AuctionDetailsRecordList auctionDetailsRecordList) {
                        if (auctionDetailsRecordList.isSuccess())
                        {
                            headbinding.tvText1.setText(String.format("竞拍记录(%s条)",auctionDetailsRecordList.getData().size()+""));
                            adapter.setNewInstance(auctionDetailsRecordList.getData());
                        }
                    }
                });
    }

    //获取有效期
    private void getNotices(String id) {
        ApiFactory.getApiService().exptime(User.get().getMyInfo().getToken()
        ,id).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<ExptimeBean>(this) {
                    @Override
                    protected void onNextInActive(ExptimeBean exptimeBean) {
                        if (exptimeBean.isSuccess())
                        {
                            binding.tvNotice.setText("竞拍所得城市"+exptimeBean.getData().getExpTime()+"天后自动解锁，并加价"+exptimeBean.getData().getUpRatio()+"%再次进行拍卖，若您对城市收益非常满意您也可以选择到期继续锁定城市");
                        }else
                        {
                            showToast(exptimeBean.getErrMessage());
                        }
                    }
                });
    }


    //初始化数据
//    private void initData() {
//        MyCityBean.DataBean  dataBean  = (MyCityBean.DataBean) getIntent().getSerializableExtra("data");
//        if (dataBean==null)
//        {
//            return;
//        }
//
//        //填充数据
//        if (headbinding!=null)
//        {
//            int  status = dataBean.getStatus();
////            状态（11：竞拍中，12：已锁定，13：盈利中，14：拍卖中，15：已售出，16：已回收）
//            switch (status)
//            {
//                case 11:
//                    headbinding.imgState.setImageResource(R.mipmap.ico_jingpaizhong);
//                    headbinding.tvTotalProfit.setText(dataBean.getUpCmProfitValue());
//                    headbinding.tvStartPrice.setText("¥"+dataBean.getStartPrice());
//                    headbinding.tvLeftTime.setText(dataBean.getEndTime());
//                    //按钮
//                    binding.btGo.setText("参与城市竞拍");
//                    break;
//                case 12:
//                    headbinding.imgState.setImageResource(R.mipmap.ico_yisuoding);
//                    headbinding.tvTextText.setText("现任城主：");
//                    headbinding.tvTextText1.setText("成交价：");
//                    headbinding.tvTextText2.setText("本次参与竞拍返佣收益：");
//                    headbinding.tvTextText2.setTextColor(getResources().getColor(R.color.red_common));
//
//                    headbinding.tvTotalProfit.setText(dataBean.getUserName());
//                    headbinding.tvStartPrice.setText("¥"+dataBean.getPrice());
//                    headbinding.tvLeftTime.setText("¥"+dataBean.getSumBidPrice());
//                    headbinding.tvLeftTime.setTextColor(getResources().getColor(R.color.red_common));
//
//                    break;
//                case 13:
//                    //盈利中
//
//                    break;
//
//
//
//
//            }
//
//
//
//        }
//
//
//
//    }

    AuctionDetailsAdapter adapter;
    private void initViews() {
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter  = new AuctionDetailsAdapter(R.layout.item_auction_details);
        binding.recyclerview.setAdapter(adapter);
        adapter.addHeaderView(getHead());
//        binding.btGo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                startActivity(new Intent(AuctionDetailsActivity.this,PayAuctionCityActivity.class));
//            }
//        });
    }

    HeadAuctionDetailsBinding headbinding;
    private View getHead() {
        headbinding = HeadAuctionDetailsBinding.inflate(getLayoutInflater());
        return  headbinding.getRoot();
    }



    public static void start(Context context, String   id) {
        Intent starter = new Intent(context, MyCityDetailsActivity.class);
        starter.putExtra("id",id);
        context.startActivity(starter);
    }



}